package de.tt.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.testng.Assert;

import de.tt.user.entity.User;

public class SessionFactoryHelper {
	private static final SessionFactory sessionFactory;

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	static {
		try {
			Configuration cfg = getConfiguration();
			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
					.applySettings(cfg.getProperties()).buildServiceRegistry();
			sessionFactory = cfg.buildSessionFactory(serviceRegistry);
		} catch (Throwable e) {
			System.err.println("Error in creating SessionFactory object."
					+ e.getMessage());
			throw new ExceptionInInitializerError(e);
		}
	}

	private static Configuration getConfiguration() {
		Configuration configuration = new Configuration();
		configuration.configure("hibernate.cfg.xml");
		for (Class<?> clazz : getAnnotationClasses(User.class.getPackage()
				.getName())) {
			configuration.addAnnotatedClass(clazz);
		}
		return configuration;
	}

	private static List<Class<?>> getAnnotationClasses(String packageName) {
		List<Class<?>> cs = new ArrayList<Class<?>>();

		try {
			for (Class<?> c : new ClassLocator(packageName).getAllClasses()) {
				if (c.getAnnotation(Entity.class) != null) {
					cs.add(c);
				}
			}
		} catch (ClassNotFoundException e) {
			System.out.println(e.getMessage());
			Assert.assertTrue(false);
		} catch (IOException e) {
			System.out.println(e.getMessage());
			Assert.assertTrue(false);
		}
		return cs;
	}

}